/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.googlecode.ivybeans.module.completion.ivyfiles;

import com.googlecode.ivybeans.facade.IvyFileUtil;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import javax.swing.text.Document;
import javax.xml.namespace.QName;
import org.netbeans.api.lexer.Token;
import org.netbeans.api.lexer.TokenHierarchy;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.api.xml.lexer.XMLTokenId;
import org.netbeans.modules.xml.schema.completion.spi.CompletionContext;
import org.netbeans.modules.xml.schema.completion.spi.CompletionModelProvider;
import org.netbeans.modules.xml.schema.model.SchemaModel;
import org.netbeans.modules.xml.schema.model.SchemaModelFactory;
import org.netbeans.modules.xml.xam.ModelSource;
import org.netbeans.modules.xml.xam.dom.AbstractDocumentModel;
import org.openide.util.lookup.Lookups;

/**
 * CompletionModelProvider for schema based completion, even when no namespace 
 * is specified in Ivy file.
 *
 * This is not used any more, only IvyFileCompletionProvider is used.
 * 
 * @author Xavier Hanin
 */
public class IvyFileCompletionModelProvider extends CompletionModelProvider {

    @Override
    public List<CompletionModel> getModels(CompletionContext context) {
        if(!isIvyFile(context)) //NOI18N
            return null;
        final SchemaModel sm = createIvyFileSchemaModel();
        if(sm == null)
            return null;        
        CompletionModel cm = new CompletionModel() {

            @Override
            public String getSuggestedPrefix() {
                return "ivy";
            }

            @Override
            public String getTargetNamespace() {
                return sm.getSchema().getTargetNamespace();
            }

            @Override
            public SchemaModel getSchemaModel() {
                return sm;
            }
        };
        return Collections.singletonList(cm);
    }
    
    private SchemaModel createIvyFileSchemaModel() {
        try {
            InputStream in = IvyFileUtil.getSchemaURL().openStream(); //NOI18N
            javax.swing.text.Document d = AbstractDocumentModel.
                    getAccessProvider().loadSwingDocument(in);
	    ModelSource ms = new ModelSource(Lookups.singleton(d), false);
            SchemaModel m = SchemaModelFactory.getDefault().createFreshModel(ms);
            m.sync();
            return m;
        } catch (Exception ex) {
            //just catch
        } 
        return null;
    }
    
    private boolean isIvyFile( CompletionContext context ) {
        List<QName> list = context.getPathFromRoot();
        if ( list!= null && list.size() >0 ) {
            QName qName = list.get( 0 );
            String root = qName.getLocalPart();
            if ("ivy-module".equals( root )) {
                return true;
            }
        }
        return "ivy-module".equals(getDocRoot(context.getBaseDocument()));
    }

    /**
     * Finds the root element of the xml document.
     */
    public static String getDocRoot(Document document) {
        TokenHierarchy th = TokenHierarchy.get(document);
        TokenSequence ts = th.tokenSequence();
        while(ts.moveNext()) {
            Token nextToken = ts.token();
            if(nextToken.id() == XMLTokenId.TAG) {
                String tagName = nextToken.text().toString();
                if(tagName.startsWith("<"))
                    return tagName.substring(1, tagName.length());
            }
        }
        return null;
    }

}
